class_name Player
extends Unit


const STATE_IDLE := "idle"
const STATE_MOVE := "move"
const STATE_DIE := "die"
const STATE_DASH := "dash"


const ANIMATION_IDLE := "idle"
const ANIMATION_MOVE := "move"
const ANIMATION_DIE := "die"
const ANIMATION_DASH := "dash"


@onready var weapon_container: WeaponContainer = $WeaponContainer
@onready var tail: Tail = $Visuals/Tail


@export_group("dash")
## 冲刺持续时间（秒）
@export var dash_duration: float = 0.5
## 冲刺时的速度倍率
@export var dash_speed_multi: float = 1.5
## 冲刺冷却时间（秒）
@export var dash_cooldown: float = 0.5

@export_group("effect")
## 受伤闪烁持续时间（秒）
@export var hurt_flash_duration: float = 0.4
## 受伤闪烁频率
@export var hurt_flash_rate: float = 30.0



var input_manager: InputManager:
	get: return _input_manager
var _input_manager: InputManager


var _left_boundary: int
var _right_boundary: int
var _top_boundary: int
var _bottom_boundary: int

# 初始化时获取可视化精灵的缩放
var _default_visuals_scale: Vector2
# 最后一次执行冲刺的时间
var _last_dash_time: int = 0

# 当前持有的武器
var _current_weapons: Array[WeaponBase] = []



func _init():
	_input_manager = InputManager.new()



func _ready():
	super._ready()
	_default_visuals_scale = visuals.scale
	_setup_unit_visuals()

	add_weapon(preload("res://resources/items/weapons/melee/punch/item_punch_1.tres"))


func _process(_delta: float):
	_input_manager.process_input()



func _setup_unit_visuals():
	visuals.setup_hurt_flash(hurt_flash_rate, hurt_flash_duration)




## 翻转精灵
func flip_sprite():
	if _input_manager.movment_direction.x > 0:
		visuals.scale = _default_visuals_scale * Vector2(-1, 1)
	elif _input_manager.movment_direction.x < 0:
		visuals.scale = _default_visuals_scale


## 角色朝向，1：右，-1：左
func character_orientation() -> int:
	if visuals.scale.x > 0:
		return -1
	else:
		return 1

## 是否可以冲刺
func can_dash() -> bool:
	return state_machine.current_node_state_name != STATE_DASH and Time.get_ticks_msec() - _last_dash_time > (dash_cooldown * 1000)


## 设置场地边界
func set_boundaries(left_boundary: int, right_boundary: int, top_boundary: int, bottom_boundary: int):
	_left_boundary = left_boundary
	_right_boundary = right_boundary
	_top_boundary = top_boundary
	_bottom_boundary = bottom_boundary


## 改变玩家位置，delta_position 为每帧的变更量
func change_position(delta_position : Vector2):
	position += delta_position
	position.x = clampf(position.x, _left_boundary, _right_boundary)
	position.y = clampf(position.y, _top_boundary, _bottom_boundary)



## 添加武器，并实例化预制件
func add_weapon(data: ItemWeapon):
	var weapon := data.weapon_perfab.instantiate() as WeaponBase
	add_child(weapon)

	weapon.setup_weapon(self, data)
	_current_weapons.push_back(weapon)
	weapon_container.update_weapon_position(_current_weapons)



func on_damage(hitbox: HitboxComponent):
	super.on_damage(hitbox)
	visuals.start_hurt_flash()
